package com.example.yaseademo

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.AdapterView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.yaseademo.bean.MessageData
import com.example.yaseademo.utils.MessageAdapter
import com.example.yaseademo.utils.MessageListener
import com.example.yaseademo.utils.SocketThread
import kotlinx.android.synthetic.main.activity_chat.*
import java.util.*
import kotlin.collections.ArrayList


//TODO:不稳定
class ChatActivity : AppCompatActivity() {

    private var client: SocketThread? = null
    private var myHandler: ChatActivity.MyHandler? = null
    private var count = 0
    private var clientTimer: Timer? = null
    
    companion object {
        const val TAG = "MainActivity"
        private val messageData: ArrayList<MessageData> = ArrayList()
        private var myAdapter: MessageAdapter? = null
        private var isOwn = false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)

        initView()
    }

    private fun initView() {
        myAdapter = MessageAdapter(messageData, applicationContext)
        lv_message.adapter = myAdapter
        lv_message.onItemLongClickListener = AdapterView.OnItemLongClickListener { _, _, position, _ ->
            val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = ClipData.newPlainText("内容：", messageData[position].message)
            cm.setPrimaryClip(clipData)
            Toast.makeText(applicationContext, "复制成功", Toast.LENGTH_SHORT).show()
            false
        }

        btn_send.setOnClickListener {
            Log.d(TAG, "onClick: 发送")
            val message = etMessage.text.toString()
            etMessage.setText("")
            //fixme: 当第一次发送的信息和第二次发送的信息相同时，发送端会丢失第二次信息,以下是补救措施。
            if (count == 1) {
                messageData.add(MessageData(message, true))
                myAdapter?.notifyDataSetChanged()
            }
            count++
            if (client?.isStart!!) {
                isOwn = true
                Log.d("发送消息", message)
                client?.sendMsg(message)
            }
        }

        btn_connect.setOnClickListener {
            setup()
        }

    }

    private fun setup() {
        myHandler = MyHandler()
        //初始化
        val ipAddress = et_ip_address.text.toString().trim()
        Log.d(TAG,"ipAddress: $ipAddress ")
        client = SocketThread(ipAddress, 9797, MessageListener { msg ->

            val bundle = Bundle()
            bundle.putString("input", msg)
            val isMessage = Message()
            isMessage.data = bundle
            myHandler?.sendMessage(isMessage)
        })
        Log.d(TAG, "setup: 启动线程")
        client?.start()
        //TODO:应该换成心跳检测
        clientTimer = Timer()
        clientTimer?.schedule(object : TimerTask() {
            override fun run() {
                if (client?.isStart!!) {
                    clientTimer?.cancel()
                    runOnUiThread {
//                        btn_send.isEnabled = true
                        Toast.makeText(applicationContext, "连接成功", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    runOnUiThread {
//                        btn_send.isEnabled = false
                        Toast.makeText(applicationContext, "连接失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }, 1000, 10000)
    }

    class MyHandler : Handler() {
        override fun handleMessage(msg: Message) {
            val input = msg.data.getString("input")
            Log.d(TAG, "处理收到的消息 :$input")
            messageData.add(MessageData(input, isOwn))
            myAdapter?.notifyDataSetChanged()
            isOwn = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        myHandler?.removeCallbacksAndMessages(null)
        clientTimer?.cancel()
    }

}
